package com.cqc.jdk8.Jutil.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cui
 * @date 2025/6/13 20:01
 * 该定时任务内部使用的是 SchedulerFutureTask，而它的run方法内有个if判断，如果为true,就继续执行下一次任务；如果为false，就停止执行定时任务。
 * 这个if判断调用的是  ScheduledFutureTask.super.runAndReset()
 **/
public class ScheduledExecutorServiceTest2 {

    static AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) {
        //ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("自定义线程池"));
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(() -> {
            count.incrementAndGet();
            System.out.println("count=" + count);
            if (count.get() == 5) {
                throw new RuntimeException("自定义异常");
            }
        }, 1, 1, TimeUnit.SECONDS);
    }


    public static class NamedThreadFactory implements ThreadFactory {
        /**
         * 线程池数量
         */
        private final AtomicInteger poolNumber = new AtomicInteger(1);
        /**
         * 线程组
         */
        private final ThreadGroup threadGroup;
        /**
         * 线程数量
         */
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        /**
         * 线程名前缀
         */
        public final String namePrefix;

        public NamedThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
            if (null == name || "".equals(name.trim())) name = "pool";
            namePrefix = name + "-" + poolNumber.getAndIncrement() + "-线程-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
            if (t.isDaemon()) t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
